package com.snatch.deal.shop.store.config;

import com.snatch.deal.shop.store.dds.DRoutingDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration  
public class DataSourceConfig {
    @Bean(name = "primary")  
    @Primary
    @ConfigurationProperties(prefix="spring.datasource.primary")
    public DataSource primaryDataSource() {  
        return DataSourceBuilder.create().build();  
    }

    /** 
     * 动态数据源设置 
     * @return 
     */  
    @Bean(name = "ddataSource")  
    public DataSource ddataSource(){  
        DRoutingDataSource dRoutingDataSource = new DRoutingDataSource();
  
        //设置默认的数据源  
        dRoutingDataSource.setDefaultTargetDataSource(primaryDataSource());  
  
        //配置多数据源  
        Map<Object, Object> ddsMap = new HashMap<>(1);
        ddsMap.put("primary", primaryDataSource());  
        dRoutingDataSource.setTargetDataSources(ddsMap);
  
        return dRoutingDataSource;  
    }  

    @Bean  
    @ConfigurationProperties(prefix = "mybatis")  
    public SqlSessionFactoryBean sqlSessionFactoryBean() {  
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();  
        sqlSessionFactoryBean.setDataSource(ddataSource());  
        return sqlSessionFactoryBean;  
    }
  
    @Bean  
    public PlatformTransactionManager transactionManager(){  
        return new DataSourceTransactionManager(ddataSource());  
    }  
}  